<?php
namespace UserSystem\Tpl;

if(!defined('P_APP')) die('P_APP not set');

use Twig_Autoloader;
use Twig_Loader_Filesystem;
use Twig_Environment;
use Twig_FunctionInterface;
use Twig_Function_Function;

use UserSystem\Tpl\TplEngineInterface;


class Twig implements TplEngineInterface
{
    /**
     * Path to templates. Usually application/views.
     * @var string
     */
    protected $template_dir;
    /**
     * Path to cache.  Usually applcation/cache.
     * @var string
     */
    protected $cache_dir;

    /**
     * Twig environment see http://twig.sensiolabs.org/api/v1.8.1/Twig_Environment.html.
     * @var Twig_Envoronment object
     */
    private $_twig_env;

    public function __construct()
    {
        // register autoloader
        Twig_Autoloader::register();

        //TODO: init paths
        $this->template_dir = P_APP.'views';
        $this->cache_dir = P_APP.'cache/twig';

        // load environment
        $loader = new Twig_Loader_Filesystem($this->template_dir, $this->cache_dir);
        $this->_twig_env = new Twig_Environment($loader, array(
            'cache'       => $this->cache_dir,
            'auto_reload' => true
        ));
        $this->function_init();
    }

    /**
     * render a twig template file
     * @param string $template template name
     * @param array $data contains all varnames
     * @param boolean $render render or return raw?
     */
    public function render($template, $data = array(), $render = false)
    {
        $ext=pathinfo($template,PATHINFO_EXTENSION);
        if(empty($ext)){
            //just try twig extension
            $template .= '.twig';
        }

        $template = $this->_twig_env->loadTemplate($template);

        if($render===true){
            return $template->render($data);
        }

        echo $template->render($data);
        exit;
    }


    /**
     * Entry point for controllers (and the likes) to register
     * callback functions to be used from Twig templates
     * @param string $name name of function
     * @param Twig_FunctionInterface $function Function pointer
     * @return void
     */
    public function register_function($name, Twig_FunctionInterface $function)
    {
        $this->_twig_env->addFunction($name, $function);
    }

    /**
     * Initialize functions
     * @return void
     */
    public function function_init()
    {
        $this->_twig_env->addFunction('asset', new Twig_Function_Function('asset'));
        $this->_twig_env->addFunction('strpos', new Twig_Function_Function('strpos'));
        $this->_twig_env->addFunction('dd', new Twig_Function_Function('dd'));

    }
}
